package com.jumi.microservice.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.AsyncResult;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 异步调用客服系统注册用户
 *
 * @author Administrator
 */
@RefreshScope
public class OkHttpUtils {

    private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);

    private static final String HTTP_JSON = "application/json; charset=utf-8";
    private static final String HTTP_FORM = "application/x-www-form-urlencoded; charset=utf-8";

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(120, TimeUnit.SECONDS)
            .readTimeout(120, TimeUnit.SECONDS)
            .writeTimeout(120, TimeUnit.SECONDS)
            .build();

    public static AsyncResult<Boolean> remoteCallCustomerService(String url, String content) {
        MediaType json = MediaType.parse(HTTP_JSON);
        RequestBody requestBody = RequestBody.create(json, content);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("异步http {} 请求失败,[url={}, param={}]", HttpMethod.POST, url, content);
                throw new RuntimeException("异步http请求失败,url:" + url);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.code() == HttpStatus.OK.value()) {
                    log.info("异步http {} 请求成功,返回码为{},请求参数为[url={}, param={}]", HttpMethod.POST, response.code(), url, content);
                } else {
                    log.error("异步http {} 请求失败,错误码为{},请求参数为[url={}, param={}]", HttpMethod.POST, response.code(), url, content);
                }
            }
        });
        return new AsyncResult(Boolean.TRUE);
    }

    public static String httpGet(String url) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        String url = "https://testsldim.yaotiao.net/admin/login/editRegister";

        //请求参数
        JSONObject json = new JSONObject();
        json.put("uid", "476601735327125504");
        json.put("userName", "qiutongxin11");
        json.put("nickName", "仇同心");
        json.put("mobile", "13436802831");

        Future<Boolean> booleanFuture = OkHttpUtils.remoteCallCustomerService(url, String.valueOf(json));
        System.out.println(booleanFuture.isDone());

    }
}
